<template>
    <div class="dicom-container">
        <!-- 工具栏 -->
        <div class="toolbar">
            <!-- <button @click="activatePanTool">平移</button>
            <button @click="activateZoomTool">缩放</button>
            <button @click="activateZoomTool">角度</button>
            <button @click="activateLengthTool">长度测量</button>
            <button @click="activateRectangleTool">矩形</button>
            <button @click="activateCircleTool">圆形</button>
            <button @click="activateTextTool">文本标注</button>
            <button @click="clearAllMeasurements">清除所有标注</button>
            <button @click="resetViewport">重置视图</button> -->
            <button @click="activateOtherTools('Pan')">平移</button>
            <button @click="activateOtherTools('Zoom')">缩放</button>
            <button @click="activateOtherTools('Angle')">角度</button>
            <button @click="activateOtherTools('Length')">长度测量</button>
            <button @click="activateOtherTools('RectangleRoi')">矩形</button>
            <button @click="activateOtherTools('EllipticalRoi')">圆形</button>
            <button @click="activateOtherTools('TextMarker')">文本标注</button>
            <button @click="clearAllMeasurements">清除所有标注</button>
            <button @click="resetViewport">重置视图</button>
            <input type="file" @change="loadDicomFile" accept=".dcm" ref="fileInput">
        </div>

        <!-- 视图区域 -->
        <div ref="viewport" class="viewport"></div>
    </div>
</template>

<script>
import dicomParser from 'dicom-parser';
import cornerstone from 'cornerstone-core';
import cornerstoneMath from 'cornerstone-math';
import cornerstoneTools from 'cornerstone-tools';
import Hammer from 'hammerjs';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
import { configureCornerstone } from '@/utils/cornerstoneConfig';

export default {
    name: 'DicomViewer',
    data() {
        return {
            currentImageId: null,
            element: null,
            dicomFiles: [],
            activeTool: null,
            tools: {
                pan: 'Pan',
                zoom: 'Zoom',
                angle: 'Angle',
                length: 'Length',
                rectangle: 'RectangleRoi',
                circle: 'EllipticalRoi',
                text: 'TextMarker'
            }
        };
    },
    mounted() {
        console.log('mounted------')
        this.initViewer();
    },
    beforeDestroy() {
        this.disableViewer();
    },
    methods: {
        async init() {
            await this.configureCornerstone();
            await this.initViewer();
        },
        async configureCornerstone() {
            // 配置图像加载器
            cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
            cornerstoneWADOImageLoader.external.dicomParser = dicomParser;

            // 配置Web Worker（可选）
            cornerstoneWADOImageLoader.webWorkerManager.initialize({
                maxWebWorkers: navigator.hardwareConcurrency || 4,
                startWebWorkersOnDemand: true
            });

            // 注册常用Loader
            cornerstoneWADOImageLoader.configure({
                beforeSend: function (xhr) {
                    // 可添加请求头等配置
                }
            });
        },
        async initViewer() {
            // 初始化元素
            this.element = this.$refs.viewport;
            cornerstone.enable(this.element);
            // cornerstoneWADOImageLoader.webWorkerManager.initialize();

            // 必须先配置外部依赖
            cornerstoneTools.external.cornerstone = cornerstone;
            cornerstoneTools.external.Hammer = Hammer;
            cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
            cornerstoneTools.external.dicomParser = dicomParser;


            // 初始化工具系统
            cornerstoneTools.init({
                globalToolSyncEnabled: true,
                showSVGCursors: true,
                touchEnabled: true, // 启用触摸支持
                mouseEnabled: true // 确保鼠标事件启用
            });

            // 配置工具样式（关键修复）
            cornerstoneTools.toolStyle.setToolWidth(2);
            cornerstoneTools.toolColors.setToolColor('rgb(255, 255, 0)');
            cornerstoneTools.toolColors.setActiveColor('rgb(0, 255, 0)');

            // 添加工具（修改后的注册方式）
            this.addTools();
            // configureCornerstone();
        },

        // 添加工具
        addTools() {
            // 清除可能存在的旧工具
            // cornerstoneTools.removeTool(cornerstoneTools.PanTool);
            // cornerstoneTools.removeTool(cornerstoneTools.ZoomTool);
            // cornerstoneTools.removeTool(cornerstoneTools.LengthTool);
            // cornerstoneTools.removeTool(cornerstoneTools.RectangleRoiTool);
            // cornerstoneTools.removeTool(cornerstoneTools.EllipticalRoiTool);
            // cornerstoneTools.removeTool(cornerstoneTools.TextMarkerTool);

            // 重新注册工具
            cornerstoneTools.addTool(cornerstoneTools.PanTool);
            cornerstoneTools.addTool(cornerstoneTools.ZoomTool);
            cornerstoneTools.addTool(cornerstoneTools.AngleTool);
            cornerstoneTools.addTool(cornerstoneTools.LengthTool);
            cornerstoneTools.addTool(cornerstoneTools.RectangleRoiTool);
            cornerstoneTools.addTool(cornerstoneTools.EllipticalRoiTool);
            cornerstoneTools.addTool(cornerstoneTools.TextMarkerTool);
        },

        async loadDicomFile(event) {
            const file = event.target.files[0];
            if (!file) return;

            try {
                // 生成图像ID
                const imageId = cornerstoneWADOImageLoader.wadouri.fileManager.add(file);
                this.currentImageId = imageId;

                // 加载并显示图像
                const image = await cornerstone.loadImage(imageId);
                cornerstone.displayImage(this.element, image);

                // 图像加载后重新激活当前工具
                if (this.activeTool) {
                    this.setTool(this.activeTool);
                }

            } catch (error) {
                console.error('加载失败:', error);
                this.$emit('error', 'DICOM文件加载失败: ' + error.message);
            }
        },
        activatePanTool() {
            cornerstoneTools.setToolActive(this.tools.pan, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.pan);
        },
        activateZoomTool() {
            cornerstoneTools.setToolActive(this.tools.zoom, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.zoom);
        },
        activateLengthTool() {
            cornerstoneTools.setToolActive(this.tools.length, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.length);
        },
        activateRectangleTool() {
            cornerstoneTools.setToolActive(this.tools.rectangle, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.rectangle);
        },
        activateCircleTool() {
            cornerstoneTools.setToolActive(this.tools.circle, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.circle);
        },
        activateTextTool() {
            cornerstoneTools.setToolActive(this.tools.text, { mouseButtonMask: 1 });
            this.deactivateOtherTools(this.tools.text);
        },
        activateOtherTools(toolName) {
            // 停用所有工具
            // cornerstoneTools.setToolPassive('Wwwc');
            // cornerstoneTools.setToolPassive('Length');
            // cornerstoneTools.setToolPassive('Angle');
            // cornerstoneTools.setToolPassive('RectangleRoi');
            this.deactivateOtherTools(toolName);
            // 激活选定工具
            cornerstoneTools.setToolActive(toolName, { mouseButtonMask: 1 });
        },
        deactivateOtherTools(activeTool) {
            Object.values(this.tools).forEach(tool => {
                if (tool !== activeTool) {
                    cornerstoneTools.setToolDisabled(tool);
                }
            });
        },
        clearAllMeasurements() {
            const toolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager;
            toolStateManager.restoreToolState({});
            cornerstone.updateImage(this.element);
        },
        resetViewport() {
            if (this.element && this.currentImageId) {
                cornerstone.reset(this.element);
                cornerstone.updateImage(this.element);
            }
        },

        disableViewer() {
            if (this.element) {
                cornerstone.disable(this.element);
            }
        }
    }
};
</script>

<style scoped>
.dicom-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.toolbar {
    padding: 10px;
    background: #f0f0f0;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.toolbar button {
    padding: 5px 10px;
    cursor: pointer;
}

.viewport {
    width: 100%;
    height: calc(100vh - 50px);
    background-color: #000;
}
</style>